#include "../include/cmd.h"

int gets_filename_command(int clientfd, cmd_t *cmd){
    //接收文件名
    char filename[100] = {0};
    int filenamelen = 0;
    recv(clientfd, &filenamelen, 4, MSG_WAITALL);
    printf("filenamelen=%d\n", filenamelen);
    recv(clientfd, &filename, filenamelen, MSG_WAITALL);
    printf("filename:%s\n", filename);

    int fd = open(filename, O_RDWR|O_CREAT, 0664);
    //接收文件内容
    size_t filelen = 0;
    recv(clientfd, &filelen, 8, MSG_WAITALL);
    printf("filecontent length=%ld\n", filelen);

    size_t recvSize = 0;
    while(recvSize < filelen){
        char buff[1000] = {0};
        int buflen = 0;
        recv(clientfd, &buflen, 4, MSG_WAITALL);
        recv(clientfd, buff, buflen, MSG_WAITALL);
        write(fd, buff, buflen);
        recvSize += buflen;
    }
    //print result 
    char msg[] = "recv file complete!";
    puts(msg);
    //send result to client
    train_t train;
    bzero(&train, sizeof(train));
    train.length = strlen(msg);
    strncpy(train.buff, msg, train.length);
    int ret = send(clientfd, &train, 4 + train.length, MSG_WAITALL);
    return ret;
}

